import { createPinia } from 'pinia'
import { defineStore } from 'pinia'

const pinia = createPinia()

export default pinia

// 用户信息store
export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    token: null,
    refreshToken: null
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAuthenticated: (state) => !!state.token
  },
  actions: {
    setUserInfo(info) {
      this.userInfo = info
    },
    setToken(token) {
      this.token = token
    },
    setRefreshToken(refreshToken) {
      this.refreshToken = refreshToken
    },
    // 保存登录结果
    saveLoginResult(result) {
      this.token = result.token
      this.refreshToken = result.refreshToken
      
      // 确保用户信息中包含id字段
      if (result.userInfo) {
        // 如果后端返回的是userId而不是id，进行转换
        if (!result.userInfo.id && result.userInfo.userId) {
          result.userInfo.id = result.userInfo.userId
        }
        this.userInfo = result.userInfo
      } else {
        this.userInfo = {}
      }
      
      // 只在store中统一处理localStorage存储，避免重复存储
      localStorage.setItem('token', result.token)
      localStorage.setItem('refreshToken', result.refreshToken)
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    logout() {
      this.userInfo = null
      this.token = null
      this.refreshToken = null
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
      localStorage.removeItem('userInfo')
    },
    loadUserInfo() {
      const token = localStorage.getItem('token')
      const refreshToken = localStorage.getItem('refreshToken')
      const userInfoStr = localStorage.getItem('userInfo')
      
      if (token && userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr)
          // 确保用户信息中包含id字段
          if (!userInfo.id && userInfo.userId) {
            userInfo.id = userInfo.userId
          }
          this.token = token
          this.refreshToken = refreshToken
          this.userInfo = userInfo
        } catch (error) {
          console.error('解析用户信息失败:', error)
          this.logout()
        }
      }
    },
    // 刷新token后的更新
    updateAfterRefresh(result) {
      this.token = result.token
      this.refreshToken = result.refreshToken
      this.userInfo = result.userInfo
      localStorage.setItem('token', result.token)
      localStorage.setItem('refreshToken', result.refreshToken)
      localStorage.setItem('userInfo', JSON.stringify(result.userInfo))
    }
  }
})

// 购物车store
export const useCartStore = defineStore('cart', {
  state: () => ({
    items: []
  }),
  getters: {
    totalItems: (state) => state.items.reduce((total, item) => total + item.quantity, 0),
    totalPrice: (state) => state.items.reduce((total, item) => total + (item.price * item.quantity), 0)
  },
  actions: {
    addToCart(product, quantity = 1) {
      const existingItem = this.items.find(item => item.id === product.id)
      if (existingItem) {
        existingItem.quantity += quantity
      } else {
        this.items.push({
          ...product,
          quantity
        })
      }
      this.saveCart()
    },
    removeFromCart(productId) {
      this.items = this.items.filter(item => item.id !== productId)
      this.saveCart()
    },
    updateQuantity(productId, quantity) {
      const item = this.items.find(item => item.id === productId)
      if (item) {
        item.quantity = quantity
        if (item.quantity <= 0) {
          this.removeFromCart(productId)
        } else {
          this.saveCart()
        }
      }
    },
    clearCart() {
      this.items = []
      this.saveCart()
    },
    saveCart() {
      localStorage.setItem('cart', JSON.stringify(this.items))
    },
    loadCart() {
      const cart = localStorage.getItem('cart')
      if (cart) {
        this.items = JSON.parse(cart)
      }
    }
  }
})

// 产品store
export const useProductStore = defineStore('product', {
  state: () => ({
    products: [],
    categories: [],
    loading: false,
    error: null
  }),
  getters: {
    getProductById: (state) => (id) => {
      return state.products.find(product => product.id === id)
    }
  },
  actions: {
    setProducts(products) {
      this.products = products
    },
    setCategories(categories) {
      this.categories = categories
    },
    setLoading(loading) {
      this.loading = loading
    },
    setError(error) {
      this.error = error
    }
  }
})